﻿using Polly;
using System;
namespace HBKY.Shop.Common.PollyHelper.PollyAttribute
{
    /// <summary>
    /// 这是一个规则
    /// </summary>
    public class CustomPollyFallbackAttribute : PollyRetryAttribute
    {
        //在这里定义策略，对外提供策略 
        public override Action<ISyncPolicy> Do(Action<ISyncPolicy> action)
        {
            var circuitBreakerPolicy = Policy
                .Handle<Exception>()
                .CircuitBreaker(
                  exceptionsAllowedBeforeBreaking: 4,             // 连续4次异常
                  durationOfBreak: TimeSpan.FromMilliseconds(10000),       // 断开1分钟
                  onBreak: (exception, breakDelay) =>
                  {
                      LogHelper.LogManagerNlog.LogError(exception, $"{DateTime.Now}:熔断了。。 {breakDelay.TotalMilliseconds } ms, 异常: {exception.Message}");
                  },
                  onReset: () => 
                  {
                      // 熔断器关闭
                      LogHelper.LogManagerNlog.LogError($"{DateTime.Now}:熔断器关闭了。。。");
                  },
                  onHalfOpen: () => 
                  {
                      // 熔断时间结束时，从断开状态进入半开状态
                      LogHelper.LogManagerNlog.LogError($"{DateTime.Now}:熔断时间到，进入半开状态。。。");
                  });

            return s =>
            {

                Policy policy = null;
                if (s == null) policy = circuitBreakerPolicy;
                else policy = Policy.Wrap(s, circuitBreakerPolicy);
                action(policy);
            };
        }
    }
}
